package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ComboDetailBean;
import com.yiwei.zxp.api.bean.CreateOrderBean;
import com.yiwei.zxp.api.bean.PayTypeBean;
import com.yiwei.zxp.api.bean.ShareGoldExplainBean;
import com.yiwei.zxp.api.model.ComboDetailModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.PaySuccessEvent;
import com.yiwei.zxp.util.Arith;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.PacketPayStepDilaog;
import com.yiwei.zxp.view.PacketPayTypeDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BoothPacketDetailActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    ImageView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_money)
    TextView txtMoney;

    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.txt_info_packet)
    TextView txtInfoPacket;
    @BindView(R.id.txt_info_use)
    TextView txtInfoUse;
    @BindView(R.id.txt_content)
    TextView txtContent;
    @BindView(R.id.img_banner)
    ImageView imgBanner;
    @BindView(R.id.btn_sub)
    ImageView btnSub;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.txt_info_one)
    TextView txtInfoOne;
    @BindView(R.id.layout_info_one)
    LinearLayout layoutInfoOne;
    @BindView(R.id.txt_info_two)
    TextView txtInfoTwo;
    @BindView(R.id.btn_recharge)
    TextView btnRecharge;
    private Unbinder unbiner;
    private int textSize26;
    private String combo_id;
    private int combo_number = 0;
    private float single_money;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booth_packet_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        textSize26 = getResources().getDimensionPixelSize(R.dimen.x26);


        String id = getIntent().getStringExtra("id");
        getComboDetail(id);
        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    return;
                }
                updateMoney(UI.toInteger(editMoney));
            }
        });
    }

    public void getComboDetail(String id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ComboDetailBean bean = new ComboDetailBean();
        bean.id = id;
        Api.api_service.getComboDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    private void setData(ComboDetailModel.DatasBean item) {
        combo_id = item.id;
        Glide.with(this).load(item.photos).into(imgBanner);
        Spanned txtMoneyContent = Spans.with(this).
                font(item.combo_name, getResources().getDimensionPixelSize(R.dimen.x36), 0xffffffff).style(Typeface.BOLD).
                font("  (" + item.number + "个商品展示位)", getResources().getDimensionPixelSize(R.dimen.x28), 0xffffffff).
                build();
        txtContent.setText(txtMoneyContent);
        combo_number = item.number;
        single_money = Float.valueOf(item.money);

        txtMoney.setText("￥" + item.money);

        Spanned txtLeft = Spans.with(this).font("套餐类型   ", textSize26, 0xff999999).
                font(item.combo_name, textSize26, 0xff333333).style(Typeface.BOLD).
                font("\n套餐总价   ", textSize26, 0xff999999).
                font(item.money + "元", textSize26, 0xff333333).style(Typeface.BOLD).
                build();
        txtInfoLeft.setText(txtLeft);

        Spanned txtRight = Spans.with(this).font("展位数量   ", textSize26, 0xff999999).
                font(+item.number + "个", textSize26, 0xff333333).style(Typeface.BOLD).
                font("\n最多可领淘淘币   ", textSize26, 0xff999999).
                font(item.shared_gold + "元", textSize26, 0xff333333).style(Typeface.BOLD).
                build();
        txtInfoRight.setText(txtRight);

//        Spanned txtPacket = Spans.with(this).font("1、淘淘币套餐是一个购买商品展示位的套餐产品。\n2、人民币100元相当于购买一个商品展示位。\n3、本平台在您购买淘淘币套餐五个月之后，会赠送5倍共享 金可用额度给您（即支付人民币100元，5个月后可获得500 淘淘币额度，以此类推）。\n4、本平台所赠送的淘淘币额度只能在本商场消费，既不可提现，也不可转赠。", textSize26, 0xff666666).
//                font("（详情可查看淘淘币说明）", textSize26, 0xffFF0030).
//                build();
        txtInfoPacket.setText(item.desc);
//        txtInfoPacket.setText(Html.fromHtml(item.desc));

//        Spanned txtUse = Spans.with(this).
//                font("1、淘淘币额度可以在本商城购买任何商品。\n2、淘淘币额度也可以兑换第三方平台的积分。\n3、淘淘币额度还可以进行话费充值、加油卡充值、交水电费等。", textSize26, 0xff666666).
//                build();
        txtInfoUse.setText(item.useful);
//        txtInfoUse.setText(Html.fromHtml(item.useful));
        updateMoney(1);
    }


    public void getPayWay() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        PayTypeBean bean = new PayTypeBean();
        bean.type = 1;
        Api.api_service.getPayWayList(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    UserInfoGlobal.setBankLimit(result.datas.bank_limit);
                    new PacketPayTypeDilaog(this).setData(result).isOver5000(Arith.mul(single_money, UI.toFloat(editMoney))).setOnChooseListener(new PacketPayTypeDilaog.OnChooseListener() {
                        @Override
                        public void onPayType(String selectPoi, String enName, String xianXia) {
                            if (enName.equals("u_line")) {
                                new PacketPayStepDilaog(BoothPacketDetailActivity.this).setOnChooseListener(new PacketPayStepDilaog.OnChooseListener() {
                                    @Override
                                    public void onSubmit() {
                                        getOrder(combo_id, UI.toString(editMoney), selectPoi, enName);
                                    }
                                }).show();


                            } else if (enName.equals("union")) {

                                Intent intent = new Intent(BoothPacketDetailActivity.this, BankPayMoneyActivity.class);
                                intent.putExtra("combo_id", combo_id);
                                intent.putExtra("payway", selectPoi);
                                intent.putExtra("num", UI.toFloat(editMoney));
                                intent.putExtra("xian_xia", xianXia);
                                intent.putExtra("need_money", Arith.mul(single_money, UI.toFloat(editMoney)));
                                intent.putExtra("pay_type", Const.PayType.BOOTH_ORDER);
                                startActivity(intent);
                                finish();
                            }


                        }
                    }).show();

                });
    }


    public void getOrder(String combo_id, String num, String payway, String enName) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        CreateOrderBean bean = new CreateOrderBean();
        bean.combo_id = combo_id;
        bean.num = num;
        bean.pay_way = payway;
        Api.api_service.getCreateOrder(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (enName.equals(Const.PayWay.ULINE)) {
                        Util.startActivity(BoothPacketDetailActivity.this, MyOrderActivity.class);
                        finish();
                    } else if (enName.equals(Const.PayWay.UNION)) {
                        ArrayList<String> orderData = new ArrayList<String>();
                        orderData.add(result.datas.order_number);
                        Intent intent = new Intent(this, BankPayMoneyActivity.class);
                        intent.putStringArrayListExtra("data", orderData);
                        intent.putExtra("need_money", Arith.mul(single_money, UI.toFloat(editMoney)));
                        intent.putExtra("pay_type", Const.PayType.BOOTH_ORDER);
                        startActivity(intent);
                        finish();
                    }


                });
    }


    public void getExplain(String keyword) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ShareGoldExplainBean bean = new ShareGoldExplainBean();
        bean.keyword = keyword;
        Api.api_service.getShareGoldExplain(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showPacketTips(this, result.datas.title, result.datas.content);
                });
    }

    @OnClick({R.id.btn_sub, R.id.btn_add})
    public void onViewClicked1(View view) {

        if (TextUtils.isEmpty(UI.toString(editMoney))) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_sub:

                if (UI.toInteger(editMoney) <= 1) {
                    return;
                }
                int numberSub = (UI.toInteger(editMoney) - 1);
                editMoney.setText(numberSub + "");
                updateMoney(numberSub);
                break;
            case R.id.btn_add:
                int number = (UI.toInteger(editMoney) + 1);
                editMoney.setText(number + "");
                updateMoney(number);
                break;
        }
    }

    private void updateMoney(int num) {
        txtInfoOne.setText(Arith.mul(single_money, num) + "");
        txtInfoTwo.setText((int)Arith.mul(combo_number, num) + "个商品展示位");
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(PaySuccessEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_recharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_recharge:
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    ToastUtil.makeText(this, "数量不能为空");
                    return;
                }

                if (UserInfoGlobal.isLogin()) {
                    getPayWay();
                } else {
                    Util.startActivity(this, LoginNewActivity.class);
                }

                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                getExplain(Const.KeyWord.SHARED_GOLD);
                break;
        }
    }
}
